<template>
  <!-- 新增、编辑监督员 -->
  <base-breadcrumb class="UpdatePersonManage-container" :title="breadcrumbTitle" :breadcrumb="!isAudit">
    <a-spin :spinning="loadingState.isDetail">
      <a-card :bordered="false">
        <title-name :title="isDisabled ? '基本信息' : '纪检员上报'" />
        <custom-form
          ref="ruleForm"
          :isValidate="true"
          :editModel="isDisabled ? 'V' : ''"
          :rules="rules"
          :form="formInfo"
          :formList="formItemList"
          @personChanged="handleSelectPerson"
        >
          <template v-slot:content>
            <div class="slot-wrapper">
              <title-name title="主要工作经验" />
              <a-form-model-item prop="content" class="ant-form-item--full requiredFormItem">
                <BaseTextarea :disabled="isDisabled" v-model="formInfo.content" />
              </a-form-model-item>
            </div>
          </template>
        </custom-form>
      </a-card>
      <div v-if="!isConsultation" class="tool-btns page-btn-right-top">
        <a-button v-if="!isDisabled" type="primary" :loading="loadingState.isDraft" @click="handleSubmit('isDraft')"
          >保存草稿</a-button
        >
        <a-button
          v-if="!isDisabled"
          class="ml12"
          type="primary"
          :loading="loadingState.isSubmit"
          @click="handleSubmit('isSubmit')"
          >提交</a-button
        >
        <a-button class="ml12" type="primary" @click="handleClose">关闭</a-button>
      </div>
    </a-spin>
    <selectApprover :businessId="businessId"  :processConfig="setProcessConfig"></selectApprover>
  </base-breadcrumb>
</template>

<script>
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 项目
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import { getSupervisorDetail, updateSupervisor } from '@/api/disciplineInspection/orgStructure/index.js'
import { getUsersDetail } from '@/api/commons'

export default {
  name:'a'+ Date.now(),
  props: {
    // 是否作为审批详情
    isAudit: {
      type: Boolean,
      default: false
    },
    // 是否作为意见征询
    isConsultation: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loadingState: {
        isDetail: false,
        isSubmit: false,
        isDraft: false,
      },
      formInfo: {
        viewName: ''
      },
      rules: {
        userId: [{ required: true, message: '请选择兼职监督员', trigger: 'change' }],
        content: [{ required: true, message: '请输入主要工作经验', trigger: 'blur' }],
        checkTime: [{ required: true, message: '请选择入职纪检时间', trigger: 'change' }],
      },
        //获取流程配置值
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      businessId: null
    }
  },
  computed: {
    pageType() {
      if (this.isAudit) {
        return 'look'
      }
      return this.$route.query.pageType || 'look'
    },
    breadcrumbTitle() {
      const map = {
        add: '监督员设置',
        edit: '监督员编辑',
        look: '监督员详情',
      }
      return map[this.pageType] || map['look']
    },
    isDisabled() {
      return this.pageType === 'look'
    },
    formItemList() {
      return [
        {
          label: '所属单位',
          keyName: 'viewName',
          viewName: 'viewName',
          type: 'BaseInput',
          disabled: true,
          span: 16
        },
        // {
        //   label: '所属项目',
        //   keyName: 'projectId',
        //   viewName: 'projectName',
        //   type: SelectProject,
        //   disabled: true,
        //   attrs: {
        //     keyValue: 'brandOrgId',
        //     form: this.formInfo,
        //     autoSelected: false,
        //     isMaintenance: true
        //   },
        // },
        {
          label: '兼职监督员',
          keyName: 'userId',
          viewName: 'name',
          type: SelectPersonByProject,
          disabled: this.isDisabled,
          attrs: {
            isOrg: true,
            orgId: this.formInfo.projectOrgId,
            showSearch: true,
            isEdit: true,
          },
        },
        {
          label: '手机号码',
          keyName: 'phone',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '身份证号码',
          keyName: 'idcard',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '性别',
          keyName: 'sex',
          type: 'a-select',
          data: [
            {
              label: '男',
              value: '1',
            },
            {
              label: '女',
              value: '0',
            },
          ],
          disabled: true,
        },
        {
          label: '政治面貌',
          keyName: 'ploicy',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '民族',
          keyName: 'nation',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '最高学历',
          keyName: 'specialitieMax',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '所学专业',
          keyName: 'specialitie',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '职称',
          keyName: 'jobTitle',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '岗位职务',
          keyName: 'postName',
          type: 'BaseInput',
          disabled: true,
        },
        {
          label: '入职纪检时间',
          keyName: 'checkTime',
          type: 'a-date-picker',
          disabled: this.isDisabled,
          attrs: {
            valueFormat: 'YYYY-MM-DD',
          },
        },
        {
          slot: true,
          keyName: 'content',
          customItemSlot: true,
          span: 24,
        },
      ]
    },
  },
 async created() {
    this.getSupervisorDetailReq()
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('supervisor_report')
  },
  methods: {
    /**
     * 用户详情
     */
    async getUsersDetailReq(id) {
      if (!id) return
      try {
        const res = await getUsersDetail({ userId: id })
        const sexMap = {
          0: '女',
          1: '男',
        }
        const { phoneNum, idCard, sex, specialitieMax, specialitie, jobTitle } = res.data
        this.formInfo = {
          ...this.formInfo,
          phone: phoneNum,
          idcard: idCard,
          sex: sexMap[sex] || '',
          specialitieMax,
          specialitie,
          jobTitle,
        }
      } catch (e) {
        console.error(e)
      }
    },
    async getSupervisorDetailReq() {
      try {
        if (!this.$route.query.id) return
        const params = {
          id: this.$route.query.id,
        }
        this.loadingState.isDetail = true
        const res = await getSupervisorDetail(params)
        this.loadingState.isDetail = false
        this.formInfo = {
          ...res.data,
          content: res.data?.inspPersonnelInfoVO?.content,
          checkTime: res.data?.inspPersonnelInfoVO?.checkTime,
          postName: res.data?.inspPersonnelInfoVO?.postName,
        }
        this.formInfo.viewName = this.formInfo.brandOrgName + "/" + this.formInfo.projectName
        this.$nextTick(() => {
          this.formInfo.projectId = res.data?.projectId
          this.formInfo.userId = res.data?.inspPersonnelInfoVO?.userId
          this.getUsersDetailReq(this.formInfo.userId)
        })
      } catch (e) {
        this.loadingState.isDetail = false
        console.error(e)
      }
    },
    /**
     * 人员选择
     * @param {String} key 改变的表单键名
     * @param {Object} data 选中人员的信息对象
     */
    handleSelectPerson(key, data = {}) {
      if (key === 'userId') {
        const { name, phoneNum, idCard, sex, specialitieMax, specialitie, jobTitle, postPNames } = data
        this.formInfo = {
          ...this.formInfo,
          name,
          phone: phoneNum,
          idcard: idCard,
          sex,
          specialitieMax,
          specialitie,
          jobTitle,
          postName: (postPNames && postPNames.join(',')) || '',
        }
      }
    },
    /**
     * 保存草稿、提交等操作
     * @param {String} actionName 'isDraft': 保存草稿  'isSubmit'：提交
     */
    handleSubmit(actionName) {
      if (actionName === 'isSubmit') {
        this.$refs.ruleForm.validate((valid) => {
          if (!valid) {
            this.$message.warning("请填写完所有必填项信息")
            return
          }
          this.invokeSave(actionName)
        })
      } else {
        this.invokeSave(actionName)
      }
    },
    /**
     * 保存接口调用
     */
    async invokeSave(actionName) {
      this.setProcessConfig = null;
      if (this.loadingState[actionName]) return
      try {
        this.loadingState[actionName] = true
        const params = {
          auditStatus: actionName === 'isSubmit' ? 1 : 0, // 0：草稿，未提交/1：已提交，待审核，审核中/2:通过/3:驳回
          id: this.$route.query.id,
          name: this.formInfo.name,
          inspPersonnelInfoDTO: {
            ...this.formInfo,
            enable: 0, // 0：启用  1：禁用
            id: this.formInfo.inspPersonnelId,
          },
        }
        // 这里只用调修改接口
        const fn = updateSupervisor
        let res = await fn(params)
        this.loadingState[actionName] = false
        this.$message.success(actionName === 'isDraft' ? '保存成功' : '提交成功')
        if(actionName=='isSubmit'){
        //提交时，返回id
          this.businessId = this.$route.query.id;
          this.setProcessConfig = this.processConfig;
          return
        }else{
          this.$multiTab.close()
        }
      } catch (e) {
        console.error(e)
        this.loadingState[actionName] = false
      }
    },
    handleClose() {
      this.$close()
    },
  },
}
</script>

<style lang="less" scoped>
.slot-wrapper {
  padding-top: 50px;
}
</style>
